package com.bigmi.user.service.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bigmi.common.smsTemplate.template.SendSms;
import com.bigmi.model.common.dtos.ResponseResult;
import com.bigmi.model.common.enums.AppHttpCodeEnum;
import com.bigmi.model.user.dtos.LoginDto;
import com.bigmi.model.user.pojos.ApUser;
import com.bigmi.model.wemedia.pojos.WmUser;
import com.bigmi.user.mapper.ApLoginMapper;
import com.bigmi.user.mapper.WmUserMapper;
import com.bigmi.user.service.ApLoginService;
import com.bigmi.utils.common.AppJwtUtil;
import com.bigmi.utils.common.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.avro.data.Json;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
@Slf4j
public class ApLoginServiceImpl extends ServiceImpl<ApLoginMapper, ApUser> implements ApLoginService {
    //@Autowired
    @Autowired
    private SendSms sendSms;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ApLoginMapper apLoginMapper;
    @Autowired
    private WmUserMapper wmUserMapper;




    /**
     * 登录注册
     * @param phone
     * @return
     */
    @Override
    public ResponseResult sendMsg(Map phone)  {
        String code = ValidateCodeUtils.generateValidateCode( 6 ).toString();
        System.out.println(code);
        String phoneNumb = String.valueOf(phone.get("phone"));
        redisTemplate.opsForValue().set(phoneNumb,code,5, TimeUnit.MINUTES);
        System.out.println(phoneNumb);
        sendSms.sendSms(phoneNumb,code);
        String o = (String) redisTemplate.opsForValue().get(phoneNumb);
        System.out.println(o+"-------------------");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    @Override
    public ResponseResult login(LoginDto loginDto) {

        //根据手机号查询信息

        if (StringUtils.isNotBlank(loginDto.getPhone()) && StringUtils.isNotBlank(loginDto.getPassword())) {
            //根据手机号查询一条
            LambdaQueryWrapper<ApUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            ApUser apUser = getOne(lambdaQueryWrapper.eq(ApUser::getPhone, loginDto.getPhone()));
            //如果用户不存在return信息
            System.out.println(apUser);
            if (apUser == null) {
              //判断当前手机号是否为新用户，如果是新用户自动完成注册
                apUser = new ApUser();
                apUser.setPhone(loginDto.getPhone());
                apUser.setStatus((short) 0);
                apLoginMapper.insert(apUser);
            }
            //从redis中获取验证码
            Object phoneNub = redisTemplate.opsForValue().get(loginDto.getPhone());
            if (!loginDto.getPassword().equals(phoneNub)){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"验证码错误");
            }
            //返回jwt
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            apUser.setStatus((short) 0);
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        } else {
            //游客登录
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }

    /**
     * 申请成为自媒体用户
     * @param wmUser
     * @return
     */
    @Override
    public ResponseResult apply(WmUser wmUser) {
        if (wmUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        LambdaQueryWrapper<WmUser> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getPhone,wmUser.getPhone());
        WmUser user = wmUserMapper.selectOne(queryWrapper);
        if (user == null){
            //严
            String key = ValidateCodeUtils.generateValidateCode(6).toString();
            wmUser.setSalt(key);
            //添加密码
            wmUser.setPassword(DigestUtils.md5DigestAsHex((wmUser.getPassword()+key).getBytes()));
            //状态暂时不可用
            wmUser.setStatus(0);
            wmUser.setCreatedTime(new Date());
            //查询作者名是否已经存在
            LambdaQueryWrapper<WmUser> wrapper =new LambdaQueryWrapper<>();
            wrapper.eq(WmUser::getName, wmUser.getName());
            WmUser selectOne = wmUserMapper.selectOne(wrapper);
            System.out.println(selectOne);
            if (selectOne!= null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"作者名已存在请更换");
            }else {
                wmUserMapper.insert(wmUser);
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }
        }
        //判断phone存在
        if (wmUser.getPhone() .equals(user.getPhone())){
//            if (user.getStatus() == 9){
//                //如果phone存在修改状态
//                wmUser.setId(wmUser.getId());
//                wmUser.setEmail(wmUser.getEmail());
//                wmUser.setCreatedTime(new Date());
//                //状态暂时不可用
//                wmUser.setStatus(0);
//                wmUserMapper.update(wmUser,queryWrapper);
//                //状态为永久可以用
//            }else if (user.getStatus() == 1){
//                return ResponseResult.okResult("您已经是自媒体无需再次申请");
//            }else if (user.getStatus() == 0){
//                return ResponseResult.okResult("请等待管理员审核");
//            }
            Integer status = user.getStatus();
            switch (status){
                //驳回自媒体申请,用户再次申请
                case (9):
                    //严
                    String key = ValidateCodeUtils.generateValidateCode(6).toString();
                    wmUser.setSalt(key);
                    //添加密码
                    wmUser.setPassword(DigestUtils.md5DigestAsHex((wmUser.getPassword()+key).getBytes()));
                    wmUser.setCreatedTime(new Date());
                    //状态暂时不可用
                    wmUser.setStatus(0);
                    wmUserMapper.update(wmUser,queryWrapper);
                    break;
                case (1):
                    return ResponseResult.errorResult(5001,"您已经是自媒体无需再次申请");
                    //break;
                case (0):
                    return ResponseResult.errorResult(5002,"请等待管理员审核");
                case (2):
                    return ResponseResult.errorResult(5003,"该账号已被禁用请重新申请");
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
